package tw.twandroidproj.app.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import tw.twandroidproj.app.MyApp;
import tw.twandroidproj.app.R;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.model.SmsCount;
import tw.twandroidproj.app.network.AuthManager;
import tw.twandroidproj.app.network.NetworkManager;
import tw.twandroidproj.app.network.OnResponseListener;
import tw.twandroidproj.app.ui.Apply.apply_state;
import tw.twandroidproj.app.ui.SelectTime.selectTime;
import tw.twandroidproj.app.ui.fragment.MainFragment;
import tw.twandroidproj.app.ui.fragment.PersonalFragment;
import tw.twandroidproj.app.ui.resume.Resume;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private AuthManager authManager;
    private NetworkManager netManager;
    private MyApp mapp;
    private String mytoken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        //核心代码.
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = getWindow();
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//
//            //给状态栏设置颜色。我设置透明。
//            window.setStatusBarColor(Color.alpha(R.color.colorPrimaryDark));
//            window.setNavigationBarColor(Color.alpha(100));
//        }
        setContentView(R.layout.activity_main);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
        mapp= (MyApp) getApplication();
        getSupportFragmentManager().beginTransaction().replace(R.id.f_container,new MainFragment(),"mainfragment").commit();
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.nav_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(), SearcherActivity.class));
            }
        });

        authManager=AuthManager.getInstance(this);
        netManager=NetworkManager.getInstance(this);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.nv_drawer_layout);
//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
//                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//        drawer.setDrawerListener(toggle);
//        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
       header_m(navigationView);
        if(authManager.isLogined()) {
            mytoken=authManager.getToken();
            new Thread(mRunnable).start();
        }
    }
    Runnable mRunnable = new Runnable() {

        public void run(){

            while(true){
                try{Thread.sleep(5*1000);}catch(InterruptedException e){break;}
                netManager.getSms_count(mytoken, new OnResponseListener<SmsCount>() {
                    @Override
                    public void onSuccess(SmsCount result) {
                        if(result.getMessages_count()==mapp.getSms_count()){mapp.setSms_symbol("0");}
                        else if(result.getMessages_count()!=mapp.getSms_count()){
                            mapp.setSms_count(result.getMessages_count());
                            mapp.setSms_symbol("1");
                        }
                    }

                    @Override
                    public void onFailed(ErrorModel errorModel) {

                    }
                });
                mHandler.sendMessage(mHandler.obtainMessage());


            }

        }

    };
    Handler mHandler = new Handler(){

        public void handleMessage(NotificationCompat.MessagingStyle.Message msg) {

            Log.v("2","b");
        }

    };
    @Override
    protected void onResume() {
        super.onResume();
        NavigationView navigation = (NavigationView) findViewById(R.id.nav_view);
        header_m(navigation);
    }
    public void header_m(NavigationView navigationView){
        View headerview=navigationView.getHeaderView(0);
        TextView textView1= (TextView) headerview.findViewById(R.id.user_text);
        TextView textView2= (TextView) headerview.findViewById(R.id.email_text);
        ImageView imageView= (ImageView) headerview.findViewById(R.id.touxiang_view);
        if(authManager.isLogined()){
            textView1.setText(authManager.getLoginUser().getNickname());
            textView2.setText(authManager.getLoginUser().getEmail());
        }
        else{
            textView1.setText("未登录");
            textView2.setText("淘兼职app");
        }
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (authManager.isLogined()) {
                    Toast.makeText(getBaseContext(), "已登录用户" + authManager.getLoginUser().getNickname(), Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                    startActivityForResult(intent, 0);
                }
            }
        });
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (authManager.isLogined()) {
                    Toast.makeText(getBaseContext(), "已登录用户" + authManager.getLoginUser().getNickname(), Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                    startActivityForResult(intent, 0);
                }
            }
        });
        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (authManager.isLogined()) {
                    Toast.makeText(getBaseContext(), "已登录用户" + authManager.getLoginUser().getNickname(), Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                    startActivityForResult(intent, 0);
                }
            }
        });
    }
    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerview=navigationView.getHeaderView(0);
        TextView textView1 = (TextView) headerview.findViewById(R.id.user_text);
        TextView textView2= (TextView) headerview.findViewById(R.id.email_text);
            if (0 == resultCode) {
                if(authManager.isLogined()){
                    textView1.setText(authManager.getLoginUser().getNickname());
                    textView2.setText(authManager.getLoginUser().getEmail());
                }
            }
            else if(1==resultCode){
                textView1.setText("未登录");
                textView2.setText("淘兼职app");
            }



        super.onActivityResult(requestCode, resultCode, data);
    }

    private long exitTime = 0;
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.nv_drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            Intent intent = new Intent(getBaseContext(), SettingsActivity.class);
//            startActivityForResult(intent, 0);
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.drawer_main) {
//            getSupportActionBar().setTitle("淘工作");

            getSupportFragmentManager().beginTransaction().replace(R.id.f_container, new MainFragment()).commit();
            NavigationView navigationView1 = (NavigationView) findViewById(R.id.nav_view);
            header_m(navigationView1);
        } else if (id == R.id.drawer_searcher) {
           startActivity(new Intent(getBaseContext(),SearcherActivity.class));
        } else if (id == R.id.drawer_personal) {
            if(authManager.isLogined()){
//                getSupportActionBar().setTitle("个人信息");
                getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.f_container, new PersonalFragment()).commit();
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }

        } else if(id==R.id.drawer_resume){
            if(authManager.isLogined()) {
                startActivity(new Intent(getBaseContext(), Resume.class));
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }
        }else if (id == R.id.drawer_select_time) {
            if(authManager.isLogined()) {
                startActivity(new Intent(getBaseContext(),selectTime.class));
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }

        } else if (id == R.id.drawer_apply) {
            if(authManager.isLogined()) {
                startActivity(new Intent(getBaseContext(),apply_state.class));
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }

        } else if (id == R.id.drawer_mytime) {
            if(authManager.isLogined()) {
                startActivity(new Intent(getBaseContext(),mytime.class));
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }

        }else if(id==R.id.drawer_offer){
            if(authManager.isLogined()) {
                startActivity(new Intent(getBaseContext(),job_create.class));
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }

        }else if(id==R.id.drawer_nettest){
            startActivity(new Intent(getBaseContext(),NetTestActivity.class));
        }
//        else if(id==R.id.drawer_applyjob){
//            startActivity(new Intent(getBaseContext(),details_job_Activity.class));
//        }
        else if(id==R.id.drawer_set){
            Intent intent = new Intent(getBaseContext(), SettingsActivity.class);
            startActivityForResult(intent, 0);
        }else if(id==R.id.drawer_seller_center){
            if(authManager.isLogined()) {
                startActivity(new Intent(getBaseContext(),SellerCenterActivity.class));
            }
            else{
                startActivity(new Intent(getBaseContext(),LoginActivity.class));
            }

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.nv_drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
